package com.example.config.handler;

import com.example.constant.Constants;
import com.example.entity.TUser;
import com.example.result.R;
import com.example.service.RedisService;
import com.example.util.JSONUtils;
import com.example.util.JWTUtils;
import com.example.util.ResponseUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private RedisService redisService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //由于禁用了session，我们在登录成功后，需要在服务器保持用户的登录状态，前端下次来访问服务器端的时候，服务器端要知道这个人登录了
        TUser tUser = (TUser) authentication.getPrincipal();

//        将用户转为json，作为负载数据放入jwt
        String userJSON = JSONUtils.toJSON(tUser);
//        1、生成jwt
        String jwt = JWTUtils.createJWT(userJSON);
//        2、写入redis中
        redisService.setValue(Constants.REDIS_JWT_KEY + tUser.getId(), jwt);
//        3、设置jwt的过期时间：勾选了记住我，则过期时间为7天，否则为30分钟
        String rememberMe = request.getParameter("rememberMe");

        System.out.println("rememberMe取值为：" + rememberMe);
        if (Boolean.parseBoolean(rememberMe)) {
            redisService.expire(Constants.REDIS_JWT_KEY + tUser.getId(), Constants.EXPIRED_TIME, TimeUnit.SECONDS);
        }else {
            redisService.expire(Constants.REDIS_JWT_KEY + tUser.getId(), Constants.DEFAULT_EXPIRED_TIME, TimeUnit.SECONDS);
        }

        R result = R.OK(jwt);

        //把R对象转成json
        String resultJSON = JSONUtils.toJSON(result);

        //把json写出去，写到浏览器
        ResponseUtils.write(response, resultJSON);
    }
}
